package com.xbfinal.oss.service.impl;


import cn.hutool.core.lang.UUID;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.xbfinal.commonUtils.Result;
import com.xbfinal.oss.Utils.ConstantPropertiesUtils;
import com.xbfinal.oss.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @Title: OssSeerviceImpl
 * @Author 笑霸fianl
 * @Package com.xbfinal.oss.service.impl
 * @Date 2023/1/2 17:06
 * @描述:
 */
@Slf4j
@Service
public class OssSeerviceImpl implements OssService {


    

    /**
     * 上传头像到oss的方法
     */
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // Endpoint以华北2（北京）为例，其它Region请按实际情况填写。
        String endpoint = ConstantPropertiesUtils.END_POINT;
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

//
//        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
//        String objectName = "exampledir/exampleobject.txt";
//        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
//        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
//        String filePath= "D:\\localpath\\examplefile.txt";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //获取文件名称
        String objectName = "";
        String originalFilename =
                UUID.randomUUID()
                        .toString()
                        .replace("-","")
                        + file.getOriginalFilename();
        try {
            //第一个参数bucketName

            //第二个参数 上传到oss的完整路径，完整路径中不能包含Bucket名称
             objectName = "gugiXueYuan/eduImage/" + originalFilename;
            //第三个参数 上传文件的输入流
            InputStream inputStream = file.getInputStream();

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 设置该属性可以返回response。如果不设置，则返回的response为空。
            putObjectRequest.setProcess("true");
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 如果上传成功，则返回200。
            log.info("返回码"+result.getResponse().getStatusCode());
        } catch (OSSException oe) {
            log.info("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            log.info("Error Message:" + oe.getErrorMessage());
            log.info("Error Code:" + oe.getErrorCode());
            log.info("Request ID:" + oe.getRequestId());
            log.info("Host ID:" + oe.getHostId());
        } catch (ClientException | FileNotFoundException ce) {
            log.info("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            log.info("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        //需要返回路径 https://gulixueyuan-edu-1.oss-cn-beijing.aliyuncs.com/%E5%A4%B4%E5%83%8F.jpg
        String url="https://gulixueyuan-edu-1.oss-cn-beijing.aliyuncs.com/"+objectName;
        return url;
    }


}
